package com.lin.fengxiu.core;

import com.lin.fengxiu.model.User;
import org.apache.tomcat.jni.Local;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName LocalUser
 * @Description TODO  存儲全局變量
 * @Author wushaopei
 * @Date 2021/3/26 7:12
 * @Version 1.0
 */
public class LocalUser {

//    private static User user;
//    private static Integer scope;

    /**
     * @Description TODO threadLocal 根据当前线程表示进行存取资源
     */
    private  static ThreadLocal<Map<String,Object>> threadLocal = new ThreadLocal<>();

    /**
     * @Description TODO Map<String,Object> 中的String为当前线程标识，Object为存储的当前线程资源，存储时不需要指定map的key,由threadLocal底层自动赋值
     * @param user
     * @param scope
     */
    public static void set(User user,Integer scope){
//        LocalUser.user = user;
//        LocalUser.scope = scope;
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("scope",scope);
        LocalUser.threadLocal.set(map);
    }

    /**
     * @Description TODO map获取当前线程资源，不需要手动填入线程标识来获取对应资源，直接使用get()，threadLocal底层自动将线程标识赋值
     * @return
     */
    public static User getUser(){
        Map<String, Object> map = LocalUser.threadLocal.get();
        User user = (User)map.get("user");
        return user;
    }

    /**
     * @Description TODO 参考 getScope() 方法说明
     * @return
     */
    public static Integer getScope(){
        Map<String, Object> map = LocalUser.threadLocal.get();
        Integer scope = (Integer)map.get("scope");
        return scope;
    }

    /**
     *  @Description TODO remove（）方法用于清除当前线程在 threadLocal 中的资源
     */
    public static void clear(){
        LocalUser.threadLocal.remove();
    }
}
